package com.example.fastshareapp;

import org.alljoyn.bus.BusAttachment;
import org.alljoyn.bus.BusException;
import org.alljoyn.bus.BusListener;
import org.alljoyn.bus.BusObject;
import org.alljoyn.bus.MessageContext;
import org.alljoyn.bus.Mutable;
import org.alljoyn.bus.SessionListener;
import org.alljoyn.bus.SessionOpts;
import org.alljoyn.bus.SessionPortListener;
import org.alljoyn.bus.SignalEmitter;
import org.alljoyn.bus.Status;
import org.alljoyn.bus.annotation.BusSignal;
import org.alljoyn.bus.annotation.BusSignalHandler;

import android.app.Application;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class ApplicationService extends Service implements Observer {

	private static final String TAG = "FastShareApp.ApplicationService";

	public static enum BusAttachmentState {
		DISCONNECTED, CONNECTED, DISCOVERING
	}

	public static enum HostChannelState {
		IDLE, NAMED, BOUND, ADVERTISED, CONNECTED
	}

	public static enum UseChannelState {
		IDLE, JOINED,

	}

	public class ApplicationBusHandler extends BusListener {
		@Override
		public void foundAdvertisedName(String name, short port,
				String namePrefix) {
			MainApp main = (MainApp) getApplication();
			main.addFoundChannel(name);
		}

		@Override
		public void lostAdvertisedName(String name, short port,
				String namePrefix) {
			MainApp main = (MainApp) getApplication();
			main.removeFoundChannel(name);
		}
	}

	public class BackgroundHandler extends Handler {
		public BackgroundHandler(Looper looper) {
			super(looper);
		}

		public void exit() {
			Message msg = m_backgroundHandler.obtainMessage(EXIT);
			m_backgroundHandler.sendMessage(msg);
		}

		public void connect() {
			Message msg = m_backgroundHandler.obtainMessage(CONNECT);
			m_backgroundHandler.sendMessage(msg);
		}

		public void disconnect() {
			Message msg = m_backgroundHandler.obtainMessage(DISCONNECT);
			m_backgroundHandler.sendMessage(msg);
		}

		public void startDiscovery() {
			Message msg = m_backgroundHandler.obtainMessage(START_DISCOVERY);
			m_backgroundHandler.sendMessage(msg);
		}

		public void cancelDiscovery() {
			Message msg = m_backgroundHandler.obtainMessage(CANCEL_DISCOVERY);
			m_backgroundHandler.sendMessage(msg);
		}

		public void requestName() {
			Message msg = m_backgroundHandler.obtainMessage(REQUEST_NAME);
			m_backgroundHandler.sendMessage(msg);
		}

		public void releaseName() {
			Message msg = m_backgroundHandler.obtainMessage(RELEASE_NAME);
			m_backgroundHandler.sendMessage(msg);
		}

		public void bindSession() {
			Message msg = m_backgroundHandler.obtainMessage(BIND_SESSION);
			m_backgroundHandler.sendMessage(msg);
		}

		public void unbindSession() {
			Message msg = m_backgroundHandler.obtainMessage(UNBIND_SESSION);
			m_backgroundHandler.sendMessage(msg);
		}

		public void advertise() {
			Message msg = m_backgroundHandler.obtainMessage(ADVERTISE);
			m_backgroundHandler.sendMessage(msg);
		}

		public void cancelAdvertise() {
			Message msg = m_backgroundHandler.obtainMessage(CANCEL_ADVERTISE);
			m_backgroundHandler.sendMessage(msg);
		}

		public void joinSession() {
			Message msg = m_backgroundHandler.obtainMessage(JOIN_SESSION);
			m_backgroundHandler.sendMessage(msg);
		}

		public void leaveSession() {
			Message msg = m_backgroundHandler.obtainMessage(LEAVE_SESSION);
			m_backgroundHandler.sendMessage(msg);
		}

		public void sendMessages() {
			Message msg = m_backgroundHandler.obtainMessage(SEND_MESSAGES);
			m_backgroundHandler.sendMessage(msg);
		}
		
		public void sendImage() {
			Message msg = m_backgroundHandler.obtainMessage(SEND_IMAGE);
			m_backgroundHandler.sendMessage(msg);
		}
		public void sendImageInfo() {
			Message msg = m_backgroundHandler.obtainMessage(SEND_IMAGEINFO);
			m_backgroundHandler.sendMessage(msg);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CONNECT:
				doConnect();
				break;
			case DISCONNECT:
				doDisconnect();
				break;
			case START_DISCOVERY:
				doDiscovery();
				break;
			case CANCEL_DISCOVERY:
				doStopDiscovery();
				break;
			case REQUEST_NAME:
				doRequestName();
				break;
			case RELEASE_NAME:
				doReleaseName();
				break;
			case BIND_SESSION:
				doBindSession();
				break;
			case UNBIND_SESSION:
				doUnbindSession();
				break;
			case ADVERTISE:
				doAdvertise();
				break;
			case CANCEL_ADVERTISE:
				doStopAdvertise();
				break;
			case JOIN_SESSION:
				doJoinSession();
				break;
			case LEAVE_SESSION:
				doLeaveSession();
				break;
			case SEND_MESSAGES:
				doSendMessage();
				break;
			case SEND_IMAGE:
				doSendImage();
				break;
			case SEND_IMAGEINFO:
				doSendImageInfo();
				break;
			case EXIT:
				getLooper().quit();
				StopBackgroundHandler();
				System.exit(0);
				break;
			default:
				break;
			}
		}
	}

	private static final int EXIT = 1;
	private static final int CONNECT = 2;
	private static final int DISCONNECT = 3;
	private static final int START_DISCOVERY = 4;
	private static final int CANCEL_DISCOVERY = 5;
	private static final int REQUEST_NAME = 6;
	private static final int RELEASE_NAME = 7;
	private static final int BIND_SESSION = 8;
	private static final int UNBIND_SESSION = 9;
	private static final int ADVERTISE = 10;
	private static final int CANCEL_ADVERTISE = 11;
	private static final int JOIN_SESSION = 12;
	private static final int LEAVE_SESSION = 13;
	private static final int SEND_MESSAGES = 14;
	private static final int SEND_IMAGE = 15;
	private static final int SEND_IMAGEINFO = 16;
	public  static final String NAME_PREFIX = "com.example.fastshareapp";
	private static final short CONTACT_PORT = 42;
	private static final String OBJECT_PATH = "/chatService";
	private static final int NOTIFICATION_ID = 0xdefaced;

	private static final int HANDLE_APPLICATION_QUIT_EVENT = 0;
	private static final int HANDLE_USE_JOIN_CHANNEL_EVENT = 1;
	private static final int HANDLE_USE_LEAVE_CHANNEL_EVENT = 2;
	private static final int HANDLE_HOST_INIT_CHANNEL_EVENT = 3;
	private static final int HANDLE_HOST_START_CHANNEL_EVENT = 4;
	private static final int HANDLE_HOST_STOP_CHANNEL_EVENT = 5;
	private static final int HANDLE_OUTBOUND_CHANGED_EVENT = 6;
	private static final int HANDLE_SENDIMAGE_CHANGED_EVENT =7;
	private static final int HANDLE_SENDIMAGEINFO_CHANGED_EVENT =8;

	private BusAttachment m_bus;
	private BusAttachmentState m_busAttachmentState;
	private SimpleInterface m_simpleInterface;
	private ChatService m_chatService;
	private String m_errorString = "";
	private MainApp m_mainApp;
	private HostChannelState m_hostChannelState;
	private SimpleInterface m_hostInterface;
	private int m_hostSessionId;
	private boolean m_isJoinToSeft;
	private UseChannelState m_useChannelState;
	private int m_useSessionId;
	private ApplicationBusHandler m_busHandler;
	private BackgroundHandler m_backgroundHandler;

	private Handler m_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLE_APPLICATION_QUIT_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): APPLICATION_QUIT_EVENT");
				m_backgroundHandler.leaveSession();
				m_backgroundHandler.cancelAdvertise();
				m_backgroundHandler.unbindSession();
				m_backgroundHandler.releaseName();
				m_backgroundHandler.exit();
				stopSelf();
			}
				break;
			case HANDLE_USE_JOIN_CHANNEL_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): USE_JOIN_CHANNEL_EVENT");
				m_backgroundHandler.joinSession();
			}
				break;
			case HANDLE_USE_LEAVE_CHANNEL_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): USE_LEAVE_CHANNEL_EVENT");
				m_backgroundHandler.leaveSession();
			}
				break;
			case HANDLE_HOST_INIT_CHANNEL_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): HOST_INIT_CHANNEL_EVENT");
			}
				break;
			case HANDLE_HOST_START_CHANNEL_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): HOST_START_CHANNEL_EVENT");
				m_backgroundHandler.requestName();
				m_backgroundHandler.bindSession();
				m_backgroundHandler.advertise();
			}
				break;
			case HANDLE_HOST_STOP_CHANNEL_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): HOST_STOP_CHANNEL_EVENT");
				m_backgroundHandler.cancelAdvertise();
				m_backgroundHandler.unbindSession();
				m_backgroundHandler.releaseName();
			}
				break;
			case HANDLE_OUTBOUND_CHANGED_EVENT: {
				Log.i(TAG, "mHandler.handleMessage(): OUTBOUND_CHANGED_EVENT");
				m_backgroundHandler.sendMessages();
			}
				break;
			case HANDLE_SENDIMAGE_CHANGED_EVENT:
			{
				Log.i(TAG, "mHandler.handleMessage(): SENDIMAGE_CHANGED_EVENT");
				m_backgroundHandler.sendImage();
				break;
			}
			case HANDLE_SENDIMAGEINFO_CHANGED_EVENT:
			{
				Log.i(TAG, "mHandler.handleMessage(): SENDIMAGEINFO_CHANGED_EVENT");
				m_backgroundHandler.sendImageInfo();
				break;
			}
			
			default:
				break;
			}
		}
	};

	public void Init() {
		m_busAttachmentState = BusAttachmentState.DISCONNECTED;
		m_simpleInterface = null;
		m_chatService = new ChatService();
		m_mainApp = null;
		m_useChannelState = UseChannelState.IDLE;
		m_hostChannelState = HostChannelState.IDLE;
		m_hostSessionId = -1;
		m_useSessionId = -1;
		m_isJoinToSeft = false;
		m_hostInterface = null;
		m_busHandler = new ApplicationBusHandler();
		m_backgroundHandler = null;
	}

	public void doAdvertise() {

		String wellKnownName = NAME_PREFIX + "."
				+ m_mainApp.getM_HostChannelName();
		Status status;
		status = m_bus.advertiseName(wellKnownName, SessionOpts.TRANSPORT_ANY);
		if (status != Status.OK) {
			m_bus.releaseName(wellKnownName);
			m_errorString = status.toString();
			return;
		}
		m_hostChannelState = HostChannelState.ADVERTISED;
		m_mainApp.setM_HostChannelState(m_hostChannelState);
	}

	public void doStopAdvertise() {
		Status status;
		String wellKnowName = ApplicationService.NAME_PREFIX + "."
				+ m_mainApp.getM_HostChannelName();
		status = m_bus.cancelAdvertiseName(wellKnowName,
				SessionOpts.TRANSPORT_ANY);
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}
		m_hostChannelState = HostChannelState.BOUND;
		m_mainApp.setM_HostChannelState(m_hostChannelState);
	}

	public void doBindSession() {
		Status status;
		SessionOpts session = new SessionOpts();
		session.isMultipoint = true;
		session.transports = SessionOpts.TRANSPORT_ANY;
		session.traffic = SessionOpts.TRAFFIC_MESSAGES;
		session.proximity = SessionOpts.PROXIMITY_ANY;

		Mutable.ShortValue contactPort = new Mutable.ShortValue(CONTACT_PORT);

		status = m_bus.bindSessionPort(contactPort, session,
				new SessionPortListener() {
					@Override
					public boolean acceptSessionJoiner(short sessionPort,
							String joiner, SessionOpts sessionOpts) {
						if (sessionPort == CONTACT_PORT) {
							return true;
						}
						return false;
					}

					@Override
					public void sessionJoined(short sessionPort, int id,
							String joiner) {
						m_hostSessionId = id;
						SignalEmitter signalEmitter = new SignalEmitter(
								m_chatService, id,
								SignalEmitter.GlobalBroadcast.Off);
						m_hostInterface = signalEmitter
								.getInterface(SimpleInterface.class);

					}

				});
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}
		m_hostChannelState = HostChannelState.BOUND;
		m_mainApp.setM_HostChannelState(m_hostChannelState);

	}

	public void doUnbindSession() {
		m_bus.unbindSessionPort(ApplicationService.CONTACT_PORT);
		m_hostInterface = null;
		m_hostChannelState = HostChannelState.NAMED;
		m_mainApp.setM_HostChannelState(m_hostChannelState);
	}

	public void doConnect() {
		org.alljoyn.bus.alljoyn.DaemonInit
				.PrepareDaemon(getApplicationContext());
		m_bus.useOSLogging(true);
		m_bus.setDebugLevel("ALLJOYN_JAVA", 7);
		m_bus.registerBusListener(m_busHandler);
		Status status;
		status = m_bus.registerBusObject(m_chatService,
				ApplicationService.OBJECT_PATH);
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}

		status = m_bus.connect();
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}

		status = m_bus.registerSignalHandlers(this);
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}

		m_busAttachmentState = BusAttachmentState.CONNECTED;

	}

	public void doDisconnect() {
		m_bus.disconnect();
		m_busAttachmentState = BusAttachmentState.DISCONNECTED;
	}

	public void doRequestName() {
		String wellKnowName = ApplicationService.NAME_PREFIX + "."
				+ m_mainApp.getM_HostChannelName();
		Status status;
		status = m_bus.requestName(wellKnowName, 0);
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}
		m_hostChannelState = HostChannelState.NAMED;
		m_mainApp.setM_HostChannelState(m_hostChannelState);
	}

	public void doReleaseName() {
		String wellKnowName = ApplicationService.NAME_PREFIX + "."
				+ m_mainApp.getM_HostChannelName();
		m_bus.releaseName(wellKnowName);
		m_hostChannelState = HostChannelState.IDLE;
		m_mainApp.setM_HostChannelState(m_hostChannelState);
	}

	public void doSendMessage() {
		String message ;
		while ((message = m_mainApp.getOutBoundItem()) != null) {
			try {
				if (m_isJoinToSeft) {
					if (m_hostInterface != null) {
						m_hostInterface.Chat(message);
						
					}
				} else {
					m_simpleInterface.Chat(message);
					
				}
			} catch (BusException e) {
				// TODO: handle exception
				Log.i(TAG,"Signal Error: "+ e.toString());
			}
		}
	}
	public void doSendImageInfo(){
		try{
			if(m_isJoinToSeft){
				if(m_hostInterface != null){
					m_hostInterface.ImageInfo(m_mainApp.getM_imageInfo().getM_name(), m_mainApp.getM_imageInfo().getM_length());
					Log.i(TAG,"Send INfo: " + m_mainApp.getM_imageInfo().getM_name()+ m_mainApp.getM_imageInfo().getM_length());
				}
			}else{
				m_simpleInterface.ImageInfo(m_mainApp.getM_imageInfo().getM_name(), m_mainApp.getM_imageInfo().getM_length());
				Log.i(TAG,"Send INfo: " + m_mainApp.getM_imageInfo().getM_name()+ m_mainApp.getM_imageInfo().getM_length());
			}
		}catch(BusException e){
			Log.i(TAG,"Signal Error: "+ e.toString());
		}
	}
	
	public void doSendImage(){
		Image image;
		while((image = m_mainApp.getOutBoundImage())!= null){
			try{
				if(m_isJoinToSeft){
					if(m_hostInterface != null){
						//m_hostInterface.ImageInfo(m_mainApp.getM_imageInfo().getM_name(), m_mainApp.getM_imageInfo().getM_length());
						m_hostInterface.Image(image.getM_name(), image.getM_count(), image.getM_data());
					}
				}else{
					//m_simpleInterface.ImageInfo(m_mainApp.getM_imageInfo().getM_name(), m_mainApp.getM_imageInfo().getM_length());
					m_simpleInterface.Image(image.getM_name(), image.getM_count(), image.getM_data());
				}
			}catch(BusException e){
				Log.i(TAG,"Signal Error: "+ e.toString());
			}
		}
	}

	public void doDiscovery() {
		Status status;
		status = m_bus.findAdvertisedName(ApplicationService.NAME_PREFIX);
		if (status != Status.OK) {
			m_errorString = status.toString();
			return;
		}
		m_busAttachmentState = BusAttachmentState.DISCOVERING;
	}

	public void doStopDiscovery() {
		m_bus.cancelFindAdvertisedName(ApplicationService.NAME_PREFIX);
		m_busAttachmentState = BusAttachmentState.CONNECTED;
	}

	public void doJoinSession() {
		if (m_hostChannelState != HostChannelState.IDLE) {
			if (m_mainApp.getM_UseChannelName().equals(
					m_mainApp.getM_HostChannelName())) {
				m_useChannelState = UseChannelState.JOINED;
				m_mainApp.setM_UseChannelState(m_useChannelState);
				m_isJoinToSeft = true;
				return;
			}
		}
		String wellKnowName = ApplicationService.NAME_PREFIX + "."
				+ m_mainApp.getM_UseChannelName();
		SessionOpts session = new SessionOpts();
		session.isMultipoint = true;
		session.transports = SessionOpts.TRANSPORT_ANY;
		session.traffic = SessionOpts.TRAFFIC_MESSAGES;
		session.proximity = SessionOpts.PROXIMITY_ANY;
		Status status;
		Mutable.IntegerValue sessionId = new Mutable.IntegerValue();
		status = m_bus.joinSession(wellKnowName, CONTACT_PORT, sessionId,
				session, new SessionListener() {
					@Override
					public void sessionLost(int sessionId) {
						m_useChannelState = UseChannelState.IDLE;
						m_mainApp.setM_UseChannelState(m_useChannelState);
					}
				});

		if (status != Status.OK && status != Status.ALLJOYN_JOINSESSION_REPLY_ALREADY_JOINED) {
			m_errorString = status.toString();
			return;
		} else {
			m_useSessionId = sessionId.value;

		}

		SignalEmitter signalEmitter = new SignalEmitter(m_chatService,
				m_useSessionId, SignalEmitter.GlobalBroadcast.Off);
		m_simpleInterface = signalEmitter.getInterface(SimpleInterface.class);
		m_useChannelState = UseChannelState.JOINED;
		m_mainApp.setM_UseChannelState(m_useChannelState);
	}

	public void doLeaveSession() {
		if (!m_isJoinToSeft) {
			m_bus.leaveSession(m_useSessionId);
		}
		m_useSessionId = -1;
		m_isJoinToSeft = false;
		m_useChannelState = UseChannelState.IDLE;
		m_mainApp.setM_UseChannelState(m_useChannelState);
	}

	@BusSignalHandler(iface = ApplicationService.NAME_PREFIX
			+ ".simpleinterface", signal = "Chat")
	public void Chat(String message) {
		String uniqueName = m_bus.getUniqueName();
		MessageContext messageContext = m_bus.getMessageContext();
		if (uniqueName.equals(messageContext)) {
			return;
		}
		if (!m_isJoinToSeft && messageContext.sessionId == m_hostSessionId) {
			return;
		}

		String nickname = messageContext.sender;
		nickname = nickname
				.substring(nickname.length() - 10, nickname.length());

		m_mainApp.remoteUserMessage(nickname, message);

	}
	
	@BusSignalHandler (iface = ApplicationService.NAME_PREFIX +".simpleinterface", signal ="Image")
	public void Image(String name, int count, byte[] data){
		String uniqueName = m_bus.getUniqueName();
		MessageContext messageContext = m_bus.getMessageContext();
		if (uniqueName.equals(messageContext)) {
			return;
		}
		if (!m_isJoinToSeft && messageContext.sessionId == m_hostSessionId) {
			return;
		}
		Image tempImage = new Image(name, count, data);
		m_mainApp.addImageIntoList(tempImage);
	}
	@BusSignalHandler (iface = ApplicationService.NAME_PREFIX +".simpleinterface", signal ="ImageInfo")
	public void ImageInfo(String name, int length) {
		ImageInfo _info = new ImageInfo(name, length);
		m_mainApp.addImageInfo(_info);
	}
	

	@Override
	public synchronized void update(Observable obs, Object obj) {
		String qualifier = (String) obj;

		if (qualifier.equals(MainApp.APPLICATION_QUIT_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_APPLICATION_QUIT_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.USE_JOIN_CHANNEL_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_USE_JOIN_CHANNEL_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.USE_LEAVE_CHANNEL_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_USE_LEAVE_CHANNEL_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.HOST_INIT_CHANNEL_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_HOST_INIT_CHANNEL_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.HOST_START_CHANNEL_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_HOST_START_CHANNEL_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.HOST_STOP_CHANNEL_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_HOST_STOP_CHANNEL_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.OUTBOUND_CHANGED_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_OUTBOUND_CHANGED_EVENT);
			m_handler.sendMessage(message);
		}
		if(qualifier.equals(MainApp.SENDIMAGE_CHANGED_EVENT)){
			Message message = m_handler.obtainMessage(HANDLE_SENDIMAGE_CHANGED_EVENT);
			m_handler.sendMessage(message);
		}
		if(qualifier.equals(MainApp.SENDIMAGEINFO_CHANGED_EVENT)){
			Message message = m_handler.obtainMessage(HANDLE_SENDIMAGEINFO_CHANGED_EVENT);
			m_handler.sendMessage(message);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public class ChatService implements SimpleInterface, BusObject {

		public void Chat(String message) throws BusException {

		}
		
		public void Image(String name, int count , byte[] data){
			
		}


		public void ImageInfo(String name, int length) throws BusException {
			
		}
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate() {
		super.onCreate();
		Init();
		StartBackgroundHandler();
		m_mainApp = (MainApp) getApplication();
		m_mainApp.addObserver(this);
		m_bus  = new BusAttachment(MainApp.PACKAGE_NAME,
				BusAttachment.RemoteMessage.Receive);
		String title = "FastShare";
		String message = "Fastshare serivce is running....";
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, 0);
		@SuppressWarnings("deprecation")
		Notification notification = new Notification(R.drawable.ic_launcher,
				null, System.currentTimeMillis());
		notification.setLatestEventInfo(this, title, message, pendingIntent);
		notification.flags |= Notification.DEFAULT_SOUND
				| Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
		startForeground(NOTIFICATION_ID, notification);
		m_backgroundHandler.connect();
        m_backgroundHandler.startDiscovery();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		m_backgroundHandler.cancelAdvertise();
		m_backgroundHandler.disconnect();
		StopBackgroundHandler();
		m_mainApp.deleteObserver(this);

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	public void StartBackgroundHandler() {
		HandlerThread thread = new HandlerThread("BackgroundHandler");
		thread.start();
		m_backgroundHandler = new BackgroundHandler(thread.getLooper());

	}

	public void StopBackgroundHandler() {
		m_backgroundHandler.exit();
	}
}
